/*
	MessageSystem.h - Singleton message system
	License: BSD
*/
#pragma once
#ifndef MESSAGE_SYSTEM_H_INCLUDED
#define MESSAGE_SYSTEM_H_INCLUDED

#include <vector>

class Message;
class Subscriber;

#ifndef MUTEX_H_INCLUDED
#include "Mutex.h"
#endif

class MessageSystem
{
	Mutex                    m_subscribers_cs;
	std::vector<Subscriber*> m_subscribers;
	static MessageSystem*    s_singleton;

	MessageSystem(); // lol

	// do not define these
	MessageSystem(const MessageSystem&);
	~MessageSystem();
	///////////////////////

public:
	static MessageSystem* GetInstance();
	
	void add_subscriber( Subscriber* sub );
	template<typename T>
	void publish_message( T* msg )
	{
		if(msg)
		{
			m_subscribers_cs.lock();
			for(unsigned int ii=0; ii<m_subscribers.size(); ++ii)
			{
				if(m_subscribers[ii] && m_subscribers[ii]->is_subscribed(msg->get_id()))
				{
					m_subscribers[ii]->add_message(new T(*msg));
				}
			}
			m_subscribers_cs.unlock();
	
			delete msg; // yes
		}
	}

	// i'm lazy so implement this later
	/*
	void remove_subscriber( Subscriber* sub );
	*/

};

#endif // MESSAGE_SYSTEM_H_INCLUDED